#!/usr/bin/env bash
#-------------------------------------------------------
#	FileName	: git-push
#	Author		：hpy
#	Date		：2024年07月08日
#	Description	：git 规范化推送 
#   https://zhuanlan.zhihu.com/p/182553920
#-------------------------------------------------------


# 仓库平台前缀,环境变量中添加
# test -z $GITEE_PREX && GITEE_PREX="https://yuan_hp:token@gitee.com/yuan_hp"
# test -z $GITEA_PREX && GITEA_PREX="http://yhp:token@120.46.47.28:3000/yhp"
# test -z $GITHUB_PREX && GITHUB_PREX="https://yuan-hp:token@github.com/yuan-hp"

test -z -$GITEE_PREX && -z $GITEA_PREX && -z $GITHUB_PREX && printf "
环境变量需要添加以下变量
GITEE_PREX="https://yuan_hp:token@gitee.com/yuan_hp"
GITEA_PREX="http://yhp:token@120.46.47.28:3000/yhp"
GITHUB_PREX="https://yuan-hp:token@github.com/yuan-hp"
"

VERSION_FILE=version.txt
# 是否打标签，不要调整该值，脚本自动设置，默认为0
TAG_ENABLE=0 

#-----------------------------------------
#函数名：ReadIni 
#功能：读取ini文件，读取成功返回状态码0，否则
#返回状态码1
#@param1：ini文件路径
#@param2：Section
#@param3：Option
#例如：ReadIni test.ini s2 Path 
#-----------------------------------------
function ReadIni(){
    fid=$1
    section=$2
    option=$3

    test ! -f $fid && echo "不存在文件$fid" && return 2
    if [ $# -eq 3 ] ; then
        local src=$(cat $fid | awk '/\['$section'\]/{f=1;next} /\[*\]/{f=0} f' |  #找出section下的所有内容
        grep $option | # 匹配option的行 
        grep '='     | # 看看是不是存在=
        cut -d'=' -f2| # 获取对应的值
        cut -d'#' -f1| # 去除注释
        cut -d';' -f1| #去除注释
        awk '{gsub(/^\s+|\s+$/, "");print}') #去掉最前面的空格
        echo $src
        test ${#src} -eq 0 && return 2 || return 0  #读取到有效数据 返回状态码0
    else
        return 2
    fi 
}

#-----------------------------------------
#函数名：WriteIni
#功能：增加，改写ini文件，若不存在指定元素
#自动添加，存在则更改，操作成功返回状态码0，
#否则返回状态码2
#@param1：ini文件路径
#@param2：Section
#@param3：Option
#@param4：value
#例如：WriteIni test.ini s2 Path value
#-----------------------------------------
function WriteIni(){
    fid=$1
    section=$2
    option=$3
    value=$4
    # if [ ${fid#*.} != ini ] ; then  
    #     echo "不是ini文件" 
    #     return 2 
    # fi 
    test ! -f $fid && echo "不存在文件$fid" && return 2
    if [ $# -eq 4 ] ; then
        local src=$(cat $fid | awk '/\['$section'\]/{f=1;next} /\[*\]/{f=0} f')  #先搜寻是否存在option
        if [ ${#src} -eq 0 ] ;then #没有匹配到section，直接新建并添加内容
            echo "[$section]" >> $fid
            echo "    $option = $value"  >> $fid
            return 0
        else
            local src=$(cat -n $fid | awk '/\['$section'\]/{f=1;next} /\[*\]/{f=0} f' | grep $option | grep '=')
            if [  ${#src} -eq 0 ] ; then #没有对应的 option 直接添加
                local last=$(cat -n $fid | awk '/\['$section'\]/{f=1;next} /\[*\]/{f=0} f' | tail -n 1)
                last=$(echo $last | cut -d' ' -f1)
                sed -i "${last}a\    $option=$value" $fid 
                return 0
            fi 
            local old_value=$(echo $src | cut -d'=' -f2 |cut -d'#' -f1 | cut -d';' -f1  )
            local idx=$(echo $src | cut -d' ' -f1)
            local newcontext="$(cat $fid|sed -n "${idx}p" |  sed "s/$old_value/$value/" |  awk '{gsub(/^\s+|\s+$/, "");print}')"
            sed -i "${idx}c\    $newcontext" $fid
            return 0       
        fi  
    fi 
}

ROOTDIR=$(pwd)
# 仓库名称
GIT_NAME="$(basename $ROOTDIR).git"

GIT_PLAT=""
CONFIG=".git/config"

function init-config() {
    GIT_PLAT=$(ReadIni $CONFIG usr paltform)
    test $? -eq 0 && echo "检测到用户需要推送的平台列表: $GIT_PLAT " && return  

    fg 
    PS3="配置你要推送的平台:" 
    choices=( 'gitee' 'gitea' 'github') # sample choices
    select dummy in "${choices[@]}"; do  # present numbered choices to user
        IFS=', ' read -ra selChoices <<<"$REPLY"
        # Loop over all numbers entered.
        for choice in "${selChoices[@]}"; do
            (( choice >= 1 && choice <= ${#choices[@]} )) || { echo "Invalid choice: $choice. Try again." >&2; continue 2; }
            # echo ${choices[choice-1]} >> $GIT_PLAT
            GIT_PLAT="$GIT_PLAT ${choices[choice-1]}"
            echo "add ${choices[choice-1]}"
        done
        WriteIni $CONFIG usr paltform "$GIT_PLAT"
        test $? -eq 0 && echo "配置成功" || echo "配置失败" 
        # All choices are valid, exit the prompt.
        break
    done
}

function giturl() {
    echo "$(echo $1 | cut -d':' -f1)://$(echo $1 | cut -d'@' -f2)"
}



#-------------------------------------------------------
# 终端分割线
#-------------------------------------------------------
function fg() {
    shellwidth=`stty size|awk '{print $2}'`
    yes "-" | sed $shellwidth'q' | tr -d '\n'
}
#-------------------------------------------------------
# 提交到的平台选择
#-------------------------------------------------------
function select-platform() {
    # echo " ------------ "
    fg
    PS3="选择你要PUSH的平台序号:"
    choices="all $GIT_PLAT exit"
    choices=($choices) # sample choices
    select dummy in "${choices[@]}"; do  # present numbered choices to user
        IFS=', ' read -ra selChoices <<<"$REPLY"
        # Loop over all numbers entered.
        for choice in "${selChoices[@]}"; do
            # Validate the number entered.
            (( choice >= 1 && choice <= ${#choices[@]} )) || { echo "Invalid choice: $choice. Try again." >&2; continue 2; }
            i=${choices[choice-1]} 
            if [[ $i == "exit" ]] ; then 
                exit 0
            elif [[ $i == "gitea" ]] ; then
                git remote set-url origin  ${GITEA_PREX}/$GIT_NAME && git push \
                && echo "Gitea:Push to  $(giturl ${GITEA_PREX}) Success"  || echo "Gitea:Push to $(giturl $GITEA_PREX)/$GIT_NAME Failed"
            elif [[ $i == "gitee" ]] ; then 
                git remote set-url origin ${GITEE_PREX}/$GIT_NAME && git push \
                && echo "Gitee:Push to $(giturl ${GITEE_PREX})/$GIT_NAME Success"  || echo "Gitee:Push to $(giturl $GITEA_PREX)/$GIT_NAME Failed"
            elif [[ $i == "github" ]] ; then 
                git remote set-url origin ${GITHUB_PREX}/$GIT_NAME && git push \
                && echo "Github:Push to $(giturl ${GITHUB_PREX})/$GIT_NAME Success"  || echo "Github:Push to $(giturl $GITEA_PREX)/$GIT_NAME Failed"
            elif [[ $i == 'all' ]] ; then
                for i in $GIT_PLAT
                do
                    if [[ "$i" == "gitea" ]] ; then 
                        git remote set-url origin   ${GITEA_PREX}/$GIT_NAME && git push \
                        && echo "Gitea:Push to $(giturl ${GITEA_PREX})/$GIT_NAME Success" || echo "Gitea:Push to $(giturl $GITEA_PREX)/$GIT_NAME Failed"  
                    elif [[ "$i" == "gitee" ]] ; then 
                        git remote set-url origin   ${GITEE_PREX}/$GIT_NAME && git push \
                        && echo "Gitee:Push to $(giturl ${GITEE_PREX})/$GIT_NAME Success" || echo "Gitee:Push to $(giturl $GITEE_PREX)/$GIT_NAME Failed" 
                    elif [[ "$i" == "github" ]] ; then 
                        git remote set-url origin   ${GITHUB_PREX}/$GIT_NAME && git push \
                        && echo "Github:Push to $(giturl ${GITHUB_PREX})/$GIT_NAME Success" || echo "Github:Push to $(giturl $GITHUB_PREX)/$GIT_NAME Failed" 
                    fi 
                done     
            fi   
        done
        # All choices are valid, exit the prompt.
        break
    done

}

#-------------------------------------------------------
# commit的类型
#-------------------------------------------------------
function commit_type() {
    # echo " -------------------- "
    fg
    PS3="commit的类型:"
    select i in exit "新功能" "直接一次修复bug" "产生diff多次修复bug" "文档" "格式" "重构" "优化" "测试" "回滚到上一个版本" "代码合并" "同步Bug" "过程或辅助工具变动" "发布版本" "备份"
    do 
        if [[ $i == "exit" ]] ; then 
            exit 0
        elif [[ $i == "新功能" ]] ; then
            git add .
            git commit -m "feat:$*" 
            break
        elif [[ $i == "直接一次修复bug" ]] ; then
            git add .
            git commit -m "fix:$*" 
            break
        elif [[ $i == "产生diff多次修复bug" ]] ; then
            git add .
            git commit -m "to:$*" 
            break
        elif [[ $i == "文档" ]] ; then
            git add .
            git commit -m "docs:$*" 
            break
        elif [[ $i == "格式" ]] ; then
            git add .
            git commit -m "style:$*" 
            break
        elif [[ $i == "重构" ]] ; then
            git add .
            git commit -m "refactor:$*" 
            break
        elif [[ $i == "优化" ]] ; then
            git add .
            git commit -m "perf:$*" 
            break
        elif [[ $i == "测试" ]] ; then
            git add .
            git commit -m "test:$*" 
            break
        elif [[ $i == "回滚到上一个版本" ]] ; then
            git add .
            git commit -m "revert:$*" 
            break
        elif [[ $i == "代码合并" ]] ; then
            git add .
            git commit -m "merge:$*" 
            break
        elif [[ $i == "同步Bug" ]] ; then
            git add .
            git commit -m "sync:$*" 
            break
        elif [[ $i == "过程或辅助工具变动" ]] ; then
            git add .
            git commit -m "chore:$*" 
            break
        elif [[ $i == "发布版本" ]] ; then
            echo "$1" > $VERSION_FILE
            git add .
            git commit -m "release:$*"
            git tag -a $1 -m "$2"  # 附注标签q
            # git tag  $1 
            if [[ $? -eq 0 ]] ; then
                echo "标签$*创建成功 "
            else
                echo "标签$*创建失败"
                exit  1  
            fi
            
            TAG_ENABLE=1
            break
        elif [[ $i == "备份" ]] ; then
            git add .
            git commit -m "backup:$*"
            break
        fi    
    done 
}

# ------------------------------------------------------------
test ${#*} -eq 0 && echo "Info:请添加commit描述" && exit 1
git status
commit_type $* 




